package com.fw.render;

import java.io.IOException;
import java.io.PrintWriter;

import com.fw.exception.RenderException;

public class TextRender extends Render {

	private static final long serialVersionUID = -6784888768188758158L;
	private static final String defaultContentType = "text/plain;charset=" + getEncoding();
	private String text;

	public TextRender(String text) {
		this.text = text;
	}

	private String contentType;

	public TextRender(String text, String contentType) {
		this.text = text;
		this.contentType = contentType;
	}

	public void render() {
		PrintWriter writer = null;
		try {
			response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);

			if (contentType == null) {
				response.setContentType(defaultContentType);
			} else {
				response.setContentType(contentType);
				response.setCharacterEncoding(getEncoding());
			}

			writer = response.getWriter();
			writer.write(text);
			writer.flush();
		} catch (IOException e) {
			throw new RenderException(e);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
}
